//
//  AddressViewController.m
//  CoolMove
//
//  Created by CA on 15/9/16.
//  Copyright (c) 2015年 CA. All rights reserved.
//

#import "AddressViewController.h"
#import <FMDB/FMDB.h>

//static const NSInteger kProvinceComponent = 1;
//static const NSInteger kCityComponent = 2;
//static const NSInteger kNationalComponent = 0;



@interface AddressViewController () <UIGestureRecognizerDelegate>
@property (weak, nonatomic) IBOutlet UIPickerView *picker;
@property (weak, nonatomic) IBOutlet UIButton *okButton;
@property (weak, nonatomic) IBOutlet UIView *popView;
@property (weak, nonatomic) IBOutlet UIView *indicatorView;
@property (weak, nonatomic) IBOutlet UIButton *CancelButton;
@property (nonatomic, strong) NSArray *cities;
@property (nonatomic, strong) NSArray *provinces;
@property (nonatomic, copy)   NSArray *nations;
@property (weak, nonatomic) IBOutlet UILabel *headTitleDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *remindDescriptionLabel;

@property (copy, nonatomic) NSString *databasePath;

@property (assign, nonatomic) BOOL isEn;


@end

@implementation AddressViewController

#pragma mark - View LifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];
    

    NSArray *languages = [NSLocale preferredLanguages];
    NSString *currentLanguage = [languages objectAtIndex:0];
    if ([currentLanguage rangeOfString:@"zh-Hans"].location != NSNotFound){
        _isEn = NO;
        _databasePath = [[NSBundle mainBundle] pathForResource:@"Location" ofType:@"db"];

    } else {
        _isEn = YES;
        _databasePath = [[NSBundle mainBundle] pathForResource:@"LocationEn" ofType:@"db"];
    }

    
    [self configureLocalization];
    [self addGestureRecognizer];
    
    self.provinces = [self provincesForCountryId:0];
    self.cities = [self citiesForProvinceId:0];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [MobClick beginLogPageView:@"BirthPage"];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"BirthPage"];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Getter/Setter

- (NSArray *)nations{
    if (!_nations) {
        
        FMDatabase *db = [FMDatabase databaseWithPath:_databasePath];
        NSMutableArray *countries = [@[] mutableCopy];
        if ([db open]) {
            FMResultSet *resultSet;
            if (_isEn) {
                resultSet = [db executeQuery:@"SELECT * FROM country_en"];
            } else {
                resultSet = [db executeQuery:@"SELECT * FROM country"];
            }
            while ([resultSet next]) {
                NSString *countryName = [resultSet stringForColumn:@"Name"];
                [countries addObject:countryName];
            }
        }
        _nations = [countries copy];
    }
    return _nations;
}

#pragma mark - IBAction

- (IBAction)cancel:(id)sender
{
    [self close];
}

- (IBAction)confirm:(id)sender
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(addressViewController:didSelectAddress:)]) {
        NSInteger i = 0;
        NSString *country = @"";
        if (_isEn) {
            NSInteger countryIndex = [self.picker selectedRowInComponent:0];
            country = self.nations[countryIndex];
            i = 1;
            
            NSString *address = [NSString stringWithFormat:@"%@",country];
            [self.delegate addressViewController:self didSelectAddress:address];
            [self close];
            return;
        }
        
        NSInteger provinceIndex = [self.picker selectedRowInComponent:i];
        NSString *province;
        if (self.provinces.count > provinceIndex) {
            province = self.provinces[provinceIndex];
        } else {
            province = @"";
        }
        
        NSInteger cityIndex = [self.picker selectedRowInComponent:i+1];
        NSString *city;
        if (self.cities.count > cityIndex) {
            city = self.cities[cityIndex];
        } else {
            city = @"";
        }
        
        NSString *address = [NSString stringWithFormat:@"%@ %@ %@",country, province, city];
        
        [self.delegate addressViewController:self didSelectAddress:address];
    }
    
    [self close];
}

#pragma mark - Private Method

- (NSArray *)provincesForCountryId:(NSInteger)countryId{
    FMDatabase *db = [FMDatabase databaseWithPath:_databasePath];
    NSMutableArray *provinces = [@[] mutableCopy];
    if ([db open]) {
        FMResultSet *resultSet;
        if (_isEn) {
            resultSet = [db executeQuery:@"SELECT * FROM province_en where CountryID = ?",[@(countryId) stringValue]];
        } else {
            resultSet = [db executeQuery:@"SELECT * FROM province where CountryID = ?",[@(countryId) stringValue]];
        }
        while ([resultSet next]) {
            NSString *provinceName = [resultSet stringForColumn:@"Name"];
            [provinces addObject:provinceName];
        }
        
        [db close];
    }
    
    return [provinces copy];
}

- (NSString *)proviceIdByProviceName:(NSString *)proviceName{
    FMDatabase *db = [FMDatabase databaseWithPath:_databasePath];
    NSString *provinceId;
    if ([db open]) {
        FMResultSet *resultSet;
        if (_isEn) {
            resultSet = [db executeQuery:@"SELECT ID FROM province_en where Name = ?", proviceName];
        } else {
            resultSet = [db executeQuery:@"SELECT ID FROM province where Name = ?", proviceName];
        }
        while ([resultSet next]) {
           provinceId =  [resultSet stringForColumn:@"ID"];
            NSLog(@"provinceId = %@",provinceId);
        }
        
        [db close];
    }
    
    return provinceId;
}


- (NSArray *)citiesForProvinceId:(NSInteger)provinceId
{
//    NSString *databasePath = [[NSBundle mainBundle] pathForResource:@"Location" ofType:@"db"];
    FMDatabase *db = [FMDatabase databaseWithPath:_databasePath];
    NSMutableArray *cities = [@[] mutableCopy];
    if ([db open]) {
        FMResultSet *resultSet;
        if (_isEn) {
            resultSet = [db executeQuery:@"SELECT * FROM city_en where ProvinceID = ?", [@(provinceId) stringValue]];
        } else {
            resultSet = [db executeQuery:@"SELECT * FROM city where ProvinceID = ?", [@(provinceId) stringValue]];
        }
        while ([resultSet next]) {
            NSString *cityName = [resultSet stringForColumn:@"Name"];
            [cities addObject:cityName];
        }
        
        [db close];
    }
    
    return [cities copy];
}

- (void)configureLocalization{
    
    [self.okButton setTitle:NSLocalizedString(@"Ok", @"确定") forState:UIControlStateNormal];
    [self.CancelButton setTitle:NSLocalizedString(@"Cancel", @"取消") forState:UIControlStateNormal];
    self.headTitleDescriptionLabel.text = LOCATION(@"Please enter address");
    self.remindDescriptionLabel.text = LOCATION(@"Please enter address correctly for promotion activities");
}

- (void)close
{
    [self dismissFromParentViewControllerWithAnimationType:DetailViewControllerAnimationTypeSlide];
}

#pragma mark - UIPicker DataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if (_isEn) {
        return 1;
    } else {
        return 2;
    }
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (_isEn) {
        if (component == 0) {
           return [self.nations count];
        } else if (component == 1) {
            return [self.provinces count];
        } else {
            return [self.cities count];
        }
    } else {
        if (component == 0) {
            return [self.provinces count];
        } else {
            return [self.cities count];
        }
    }
    

}

#pragma mark - UIPicker Delegate

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (_isEn) {
        if (component == 0) {
            NSInteger countryId = [pickerView selectedRowInComponent:0];
            self.provinces = [self provincesForCountryId:countryId];
            NSInteger provinceId = -1;
            if (self.provinces.count > 0) {
                provinceId = [[self proviceIdByProviceName:self.provinces[0]] integerValue];
            }
            self.cities = [self citiesForProvinceId:provinceId];
            NSLog(@"----------->%@,%@",self.provinces,self.cities);
            [pickerView reloadAllComponents];
        }
        if (component == 1 && self.provinces.count > 0) {
            NSInteger selectIndex = [pickerView selectedRowInComponent:1];
           
            NSInteger provinceId = [[self proviceIdByProviceName:self.provinces[selectIndex]] integerValue];
            self.cities = [self citiesForProvinceId:provinceId];
            [pickerView reloadComponent:2];
        }
    } else {
        if (component == 0) {
            NSInteger provinceId = [pickerView selectedRowInComponent:0];
            self.cities = [self citiesForProvinceId:provinceId];
            [pickerView reloadComponent:1];
        }
    }
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view{
    NSString *rowStr = nil;
    
    if (_isEn) {
        if (component == 0) {
            if (self.nations.count > row) {
                rowStr = self.nations[row];
            }
        } else if (component == 1) {
            if (self.provinces.count>row) {
                rowStr = self.provinces[row];
            }
        } else {
            if (self.cities.count>row) {
                rowStr = self.cities[row];
            }
        }
    } else {
        if (component == 0) {
            rowStr = self.provinces[row];
        } else {
            rowStr = self.cities[row];
        }
    }

    UILabel* tView = (UILabel*)view;
    if (!tView)
    {
        tView = [[UILabel alloc] init];
        tView.textColor = [UIColor colorWithHex:0x7c7c7e];
        if (_isEn) {
            [tView setFont:[UIFont fontWithName:@"Helvetica" size:20]];
        } else {
            [tView setFont:[UIFont fontWithName:@"Helvetica" size:25]];
        }
        
        [tView setTextAlignment:NSTextAlignmentCenter];
        tView.numberOfLines=3;
    }
    // Fill the label text here
    tView.text= rowStr;
    return tView;
}

#pragma mark - Private Method

- (void)addGestureRecognizer
{
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(close)];
    gestureRecognizer.cancelsTouchesInView = NO;
    gestureRecognizer.delegate = self;
    [self.view addGestureRecognizer:gestureRecognizer];
}
#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return self.view == touch.view;
}

@end
